﻿package view
{
	
	import com.google.maps.LatLng;
	
	import control.AddMarker;
	import control.EditMarker;
	import control.SendMessage;
	import control.ShareMarker;
	import control.SharePhoto;
	import control.ShowAllShareMarkers;
	
	import flash.display.Loader;
	import flash.events.*;
	import flash.net.*;
	
	import model.ModelLocator;
	
	import mx.containers.Canvas;
	import mx.containers.Form;
	import mx.containers.FormItem;
	import mx.containers.TabNavigator;
	import mx.containers.VBox;
	import mx.controls.*;
	import mx.core.UIComponent;
	import mx.events.*;
	import mx.rpc.events.ResultEvent;
	import mx.rpc.http.HTTPService;
	
	import vo.MyMarker;
	
	public class MyInforWindow extends UIComponent
	{
		public var tabNavigator:TabNavigator = new TabNavigator();
		public var myform:Form = new Form();
		
		public var markernameFormItem:FormItem = new FormItem();
		public var createrFormItem:FormItem = new FormItem();
		public var typeFormItem:FormItem = new FormItem();
		public var latitudeFormItem:FormItem = new FormItem();
		public var longitudeFormItem:FormItem = new FormItem();
		public var descriptionFormItem:FormItem = new FormItem();
		public var infowin:view.MyInforWindow;
		public var markername:TextArea = new TextArea();
		public var creater:TextArea = new TextArea();
		public var type:ComboBox = new ComboBox();
		public var latitude:TextArea = new TextArea();
		public var longitude:TextArea = new TextArea();
		public var description:TextArea = new TextArea();
		
		public var canvas:Canvas = new Canvas();
		
		public var edit:Button = new Button();
		public var save:Button = new Button();
		public var share:Button = new Button();
		
		private var instance:ModelLocator = ModelLocator.getInstance();
		public var marker:MyMarker;
		private var dbAddMarker:AddMarker;
		private var dbEditMarker:EditMarker = new EditMarker();
		private var dbShareMarker:ShareMarker = new ShareMarker();
		private var dbShowAllMarkers:ShowAllShareMarkers;
		private var dbSendMessage:SendMessage = new SendMessage();
		private var dbsharephoto:SharePhoto = new SharePhoto();
		public var beSaved:Boolean = false;
		
		public var labprogress:Label = new Label();
		public var progressbar:ProgressBar = new ProgressBar();
		public var uploadphoto:Button = new Button();
		public var uploadmusic:Button = new Button();
		public var vbox:VBox = new VBox();
		public var file: FileReference;
		public var path:String;
		public var isphoto:Boolean = true;
		public var uploadcan:Canvas = new Canvas();
		public var MarkerView:view.Markers;
		public var sharephoto:Button;
		public var messagelabel:Label = new Label();
		public var message:Canvas = new Canvas();
		public var messagetext:TextArea = new TextArea();
		public var messagebutton:Button = new Button();
		public var img:Image;
		public var photourl:String = null; 
		public var musicurl:String = null; 
		[Bindable]
        public var types: Array = [ {label:"restaurant", data:1}, 
                {label:"hotel", data:2}, {label:"ports", data:3}];
                
		public function MyInforWindow(mark:view.Markers)
		{
			this.MarkerView = mark;
			this.dbAddMarker = new AddMarker(this.MarkerView,this);
			this.dbShowAllMarkers = new  ShowAllShareMarkers(this.MarkerView);
			edit.width = 62;
			edit.label = "edit";
			edit.x = 109;
			edit.y = -1;
			edit.addEventListener(MouseEvent.CLICK,editMarker);
			instance.addEventListener(ModelLocator.ADDMARKER_OK,refreshhandler);
			save.width = 62;
			save.label = "save";
			save.x = 23;
			save.y = -1;
			save.addEventListener(MouseEvent.CLICK,saveMarker);
			share.width = 62;
			share.label = "share";
			share.x = 179;
			share.y = -1;
			share.addEventListener(MouseEvent.CLICK,shareMarker);
			instance.addEventListener(ModelLocator.SHAREMARKER_OK,shareOKhandler);
			canvas.addChild(edit);
			canvas.addChild(save);
			canvas.addChild(share);
			
			markername.width = 140;
			markername.height = 19;
			markername.editable = false;
			markernameFormItem.width = 250;
			markernameFormItem.height = 20;
			markernameFormItem.label = "markername";
			markernameFormItem.addChild(markername); 
			
			creater.width = 140;
			creater.height = 19;
			creater.editable = false;
			createrFormItem.width = 250;
			createrFormItem.height = 20;
			createrFormItem.label = "creater";
			createrFormItem.addChild(creater); 
			
			type.width = 140;
			type.height = 19;
			type.editable = false;
			type.dataProvider = types;
			typeFormItem.width = 250;
			typeFormItem.height = 20;
			typeFormItem.label = "type";
			typeFormItem.addChild(type); 
			
			latitude.width = 140;
			latitude.height = 19;
			latitude.editable = false;
			latitudeFormItem.width = 250;
			latitudeFormItem.height = 20;
			latitudeFormItem.label = "latitude";
			latitudeFormItem.addChild(latitude); 
			
			longitude.width = 140;
			longitude.height = 19;
			longitude.editable = false;
			longitudeFormItem.width = 250;
			longitudeFormItem.height = 20;
			longitudeFormItem.label = "longitude";
			longitudeFormItem.addChild(longitude);
			
			description.width = 140;
			description.height = 19;
			description.editable = false;
			descriptionFormItem.width = 250;
			descriptionFormItem.height = 20;
			descriptionFormItem.label = "description";
			descriptionFormItem.addChild(description);
			
			myform.addChild(markernameFormItem);
			myform.addChild(createrFormItem);
			myform.addChild(typeFormItem);
			myform.addChild(latitudeFormItem);
			myform.addChild(longitudeFormItem);
			myform.addChild(descriptionFormItem);
			myform.addChild(canvas);
			
			labprogress.text = "upload photos:";
			progressbar.minimum = 0;
			progressbar.maximum = 100;
			progressbar.label = "current process: 0%";
			progressbar.labelPlacement = "bottom";
			progressbar.direction = "right";
			progressbar.mode = "manual";
			progressbar.width = 250;
			progressbar.visible = true;
			
			uploadphoto.label = "upload photo";
			uploadphoto.addEventListener(MouseEvent.CLICK,douploadphoto);
			uploadmusic.label = "upload music";
			uploadmusic.addEventListener(MouseEvent.CLICK,douploadmusic);
			uploadcan.percentHeight = 40;
			uploadcan.percentWidth = 100;
			uploadphoto.x = 10;
			uploadphoto.y = 10;
			uploadmusic.x = 130;
			uploadmusic.y = 10;
			uploadcan.addChild(uploadphoto);
			uploadcan.addChild(uploadmusic);
			vbox.addChild(labprogress);
			vbox.addChild(progressbar);
			vbox.addChild(uploadcan);
			vbox.x = 15;
			vbox.y = 5;
			vbox.width = 260;
			file = new FileReference();    
			file.addEventListener(ProgressEvent.PROGRESS, onProgress);    
			file.addEventListener(Event.SELECT, onSelect);    
			file.addEventListener(Event.COMPLETE, completeHandle);   
				
			message.addChild(messagelabel);
			message.addChild(messagetext);
			message.addChild(messagebutton);
			messagelabel.text = "write down your point:";
			messagelabel.x = 10;
			messagelabel.y = 10;
			messagelabel.height = 15;
			messagelabel.percentWidth = 100;
			messagetext.x = 10;
			messagetext.y = 40;
			messagetext.percentWidth = 100;
			messagetext.height = 100;
			messagebutton.x = 120;
			messagebutton.y =  150
			messagebutton.label = "commit";
			messagebutton.addEventListener(MouseEvent.CLICK,dosendmessage);
			tabNavigator.width = 300;
			tabNavigator.height = 250;
			tabNavigator.addChild(myform);
			myform.label = "information";
			tabNavigator.addChild(vbox);
			vbox.label = "upload";
			tabNavigator.addChild(message);
			tabNavigator.addChild(createPhotoTab("Photo"));
			message.percentHeight = 100;
			message.percentWidth = 100;
			message.label = "message";
			addChild(tabNavigator);
			instance.addEventListener(ModelLocator.SHAREPHOTO_OK,sharePhotoOKHandler);
			this.infowin = this;
		}
		
		public function sharePhotoOKHandler(e:Event):void{
		//	Alert.show("share photo OK");
		}
		
		public function createPhotoTab(label:String):VBox{
  			var can:VBox = new VBox();
  			can.label=label;
  			var inside:Canvas= new Canvas();
  			sharephoto = new Button();
  			sharephoto.addEventListener(MouseEvent.CLICK,dosharephoto);
  			sharephoto.label = "share";
  			sharephoto.x  = 10;
  			sharephoto.y  = 120;
  			
  			inside.width = 600;
  			inside.height = 200;
  			img = new Image();
  			img.x=0;
  			img.y=0;
  			img.width=300;
  			img.height=100;
  			/*var request:URLRequest = new URLRequest(photourl);
        	var imageLoader:Loader = new Loader();
        	imageLoader.contentLoaderInfo.addEventListener(Event.COMPLETE,function(e:Event):void{ 
				img.source = e.currentTarget.content;
 			}); 
  			imageLoader.load(request);*/
  			
  			inside.addChild(img);
  			inside.addChild(sharephoto);
  			can.addChild(inside);
  			return can;
  		}
  		
  		private function dosharephoto(e:MouseEvent):void{
  			Alert.show(this.marker.photoid + "chai here");
  			dbsharephoto.doSharePhoto(this.marker.photoid);
  		}
  		
		public function douploadphoto(e:MouseEvent):void{
			var imageTypes:FileFilter = new FileFilter("Images (*.jpg, *.jpeg, *.png, *.bmp)", "*.jpg;*.jpeg;*.png;*.bmp");    
			var allTypes:Array = new Array(imageTypes);    
			file.browse(allTypes);    
		}
		
		public function douploadmusic(e:MouseEvent):void{
			var musicTypes:FileFilter = new FileFilter("Music (*.wma, *.mp3, *.wav)", "*.wma;*.mp3;*.wav");    
			var allTypes:Array = new Array(musicTypes);
			isphoto = false;    
			file.browse(allTypes);    
		}
		
		public function dosendmessage(e:MouseEvent):void{
			dbSendMessage.doSendMessage(messagetext.text,this.marker.id,instance.user.user_name);
		}
		
		private function onProgress(e: ProgressEvent): void{    
			labprogress.text = " has uploaded " + e.bytesLoaded    
			+ " bytes，total " + e.bytesTotal + " bytes";    
			var proc: uint = e.bytesLoaded / e.bytesTotal * 100;    
			progressbar.setProgress(proc, 100);    
			progressbar.label= "the current process: " + " " + proc + "%";    
		}  
			
		private function onSelect(e: Event): void{    
			Alert.show("upload " + file.name + " (total: "+Math.round(file.size)+" bytes)?",    
			"yes,upload",Alert.YES|Alert.NO,null, proceedWithUpload);    
		}   
		
		private function proceedWithUpload(e: CloseEvent): void{
			if(this.beSaved == false){
				Alert.show("Please save the marker first.");
			}else{
				path= creater.text + "\\" + markername.text;    
				if (e.detail == Alert.YES){    
					if(isphoto == true){
						var request: URLRequest = new URLRequest("http://localhost:8080/flexMapApp/servlet/MyUploadPhoto?username="
						+creater.text +"&&userid="+instance.user.user_id +"&&markername=" + this.marker.markername);
						//Alert.show(this.marker.id);
						
						try {    
							file.upload(request); 
							//Alert.show("here i am"); 
						} catch (error:Error) {    
							Alert.show("error"); 
						}    
					}else{
						var request:URLRequest = new URLRequest("http://localhost:8080/flexMapApp/servlet/MyUploadMusic?path="
						+path +"&&markerid="+this.marker.id);
						try{
							file.upload(request);
						}catch (error:Error) {    
							Alert.show("error"); 
						}    
					}  
				}
			}    
		}
		
		private function completeHandle(event:Event):void{
			    Alert.show("Congratulations，upload successfully");
			    var getPhotourlHttp:HTTPService = new HTTPService();
			    getPhotourlHttp.url="http://localhost:8080/flexMapApp/servlet/GetPhotoURL";
			    getPhotourlHttp.addEventListener(ResultEvent.RESULT,getPhotourlOkHandler);   
			    var params:URLVariables = new URLVariables();
				params.markername = this.marker.markername;
				params.userid = instance.user.user_id;
	//			Alert.show( this.marker.id);
				getPhotourlHttp.send(params);
		} 
		public function getPhotourlOkHandler(e:ResultEvent):void{
				var photourl:String;
				if((photourl=e.result.URL)!=""){
					
					var request:URLRequest = new URLRequest(photourl);
        			var imageLoader:Loader = new Loader();
        			imageLoader.contentLoaderInfo.addEventListener(Event.COMPLETE,function(e:Event):void{ 
						img.source = e.currentTarget.content;
						Alert.show(photourl);
 					}); 
  					imageLoader.load(request);
				}
		}
		public function change(markername:String,creater:String,
		type:String,latitude:String,longitude:String,description:String,
		id:String,musicurl:String,photourl:String,photoid:String):void{
			//Alert.show("begin change");
			
			this.markername.text = markername;
			this.creater.text = creater;
			this.type.text  = type;
			this.latitude.text = latitude;
			this.longitude.text = longitude;
			this.description.text = description;
			this.marker = new MyMarker(markername,creater,type,latitude,longitude,
			description,id,musicurl,photourl,photoid);
			this.photourl = photourl;
			this.musicurl = musicurl;
			//this.photoid=photoid;
			
			if(photourl!=null){
				
				var request:URLRequest = new URLRequest(photourl);
        		var imageLoader:Loader = new Loader();
        		imageLoader.contentLoaderInfo.addEventListener(Event.COMPLETE,function(e:Event):void{ 
					img.source = e.currentTarget.content;
			//		Alert.show(photourl);
 				}); 
 		//		Alert.show(this.photourl);
  				imageLoader.load(request);
			}
			else
				this.sharephoto.enabled = false;
			
		}
		
		public function changeManageEditable(e:Boolean):void{
           		markername.editable=e;
            	type.editable=e;
            	description.editable=e;
        }
        
        public function changeLatLng(e:LatLng):void{
         		clearall();
         		creater.text = instance.user.user_name;
            	latitude.text=e.lat().toString();
            	longitude.text=e.lng().toString();
            	save.enabled = true;
         }
         
         private function clearall():void{
         		markername.text=null;
            	creater.text=null;
            	latitude.text=null;
            	longitude.text=null;
            	description.text=null;
         }
         
         private function saveMarker(e:MouseEvent):void{
         	edit.enabled = true;
            marker = new MyMarker(markername.text, instance.user.user_name, type.text,
            			latitude.text, longitude.text, description.text,null,null,null,null);
            instance.addEventListener(ModelLocator.ADDMARKER_OK,AddMarkerOKHandler);
            Alert.show(marker.markername);
            dbAddMarker.doAddMarker(marker);
            changeManageEditable(false);
            share.enabled = false;
            save.enabled = false;
         }
         private function AddMarkerOKHandler(e:Event):void{
       //  	Alert.show("hihi");
         //	Alert.show(instance.MarkerId.toString());
         	marker.id = instance.MarkerId;
         }
         
         private function  editMarker(e:MouseEvent):void{
         	if(edit.label == 'edit'){
        		changeManageEditable(true);
        		edit.label = 'ok?';
        	}else{
        		changeManageEditable(false);
      
        		var id:String = marker.id;
        		var musicurl:String = marker.musicurl;
        		var photourl:String = marker.photourl;
        		var photoid:String = marker.photoid;
        		marker = new MyMarker(markername.text, instance.user.user_name, type.text,
            				latitude.text, longitude.text, description.text,id,musicurl,photourl,photoid);
				dbEditMarker.doEditMarker(marker);
        		edit.label = 'edit';
        	}
         }
         
         public function getMarker():MyMarker{
			return marker;
		}
		
		private function shareMarker(e:MouseEvent):void{
			Alert.show("i am here in share marker");
            dbShareMarker.doShareMarker(this.marker.id);
            
         } 
         
         private function shareOKhandler(e:Event):void{
         	instance.allShowAllShareMarkers.addItem(instance.addAMarkerShare);
         	dbShowAllMarkers.doShowAllShareMarkers();
         }
         private function refreshhandler(e:Event):void{
         	Alert.show("hhhh");
			Alert.show("chaihere:"+this.marker.id);
         }
      

	}
}